package main.activities;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import main.namespace.R;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ConexaoEmuladoresActivity extends Activity {
	/** Called when the activity is first created. */
	TextView textView1;
	EditText editText1;
	ServerSocket server;
	Socket clie;
	public static DataInputStream in;
	public static DataOutputStream out;
	
	public void showMessage(final String a)
	{
		runOnUiThread(new Runnable()
		{
			public void run()
			{
				textView1.setText(a);
			}
		});
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.sock);

		textView1 = (TextView) findViewById(R.id.textView1);
		editText1 = (EditText) findViewById(R.id.editText1);
		Button serv = (Button) findViewById(R.id.bserver);
		serv.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				new Thread()
				{
					public void run()
					{
						try{
							server = new ServerSocket(8001);

							System.out.println("i came here OK");
							clie = server.accept();

							System.out.println("Connection OK");
							//m.set(clie);

							set(clie);
							
							Intent i = new Intent(getApplicationContext(), BattlefieldActivity.class);
							startActivity(i);
						}
						catch (Exception e)
						{
							showMessage("ERROR:" + e.getMessage());
						}
					}
				}.start();

			}
		});
		
		Button cli = (Button) findViewById(R.id.bclient);
		cli.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				new Thread()
				{
					public void run()
					{
						try {
							clie = new Socket("10.0.2.2", 8000);
							
							System.out.println("i came here client OK");

							//m.set(clie);
							set(clie);

							Intent i = new Intent(getApplicationContext(), BattlefieldActivity.class);
							startActivity(i);
						}
						catch (Exception e)
						{
							showMessage("ERROR:" + e.getMessage());
						}
					}
				}.start();
			}
		});
	}

	public void set(Socket client)
	{
		try
		{
			in = new DataInputStream(client.getInputStream());
			out = new DataOutputStream(client.getOutputStream());
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}